import json
import os
import logging

# 创建日志记录器
def create_logger():
    logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s | 文件:%(filename)s,函数:%(funcName)s')
    return logging


# 加载语言数据
def load_language_data():
    # 默认语言数据
    default_data = {
        "current_language": "zh",
        "zh": {
            "app_title": "图像处理器",
            "error": "错误",
            "no_image_loaded": "没有载入任何图像",
            "gray_required": "此功能只能在灰度图上使用"
        },
        "en": {
            "app_title": "Image Processor",
            "error": "Error",
            "no_image_loaded": "No image loaded",
            "gray_required": "This function only works on grayscale images"
        }
    }

    try:
        current_dir = os.path.dirname(os.path.abspath(__file__))
        json_path = os.path.join(current_dir, 'language.json')
        
        if not os.path.exists(json_path):
            print(f"Warning: language.json not found at {json_path}, using default language data")
            return default_data

        # 尝试读取文件
        with open(json_path, 'r', encoding='utf-8') as f:
            try:
                language_data = json.load(f)
                if not isinstance(language_data, dict):
                    print("Warning: language.json content is not a dictionary, using default language data")
                    return default_data
                
                # 确保必要字段存在
                if "current_language" not in language_data:
                    language_data["current_language"] = "zh"
                
                return language_data
            except json.JSONDecodeError as e:
                print(f"Warning: Failed to parse language.json: {str(e)}, using default language data")
                return default_data

    except Exception as e:
        print(f"Warning: Unexpected error loading language.json: {str(e)}, using default language data")
        return default_data

# 写入语言数据
def write_language_data(language_data, key, value):
    language_data[key] = value
    with open('language.json', 'w', encoding='utf-8') as f:
        json.dump(language_data, f, ensure_ascii=False, indent=4)


#################### 以下是载入代码 ####################
language_data = load_language_data()
logging = create_logger()
    
    

